package is.pricewatcher;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class ResultActivity extends Activity {
	private LocationManager locationManager;
	
	private final LocationListener gpsLocationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        	TextView GPS = (TextView) findViewById(R.id.Location_gps);
            switch (status) {
            case LocationProvider.AVAILABLE:
                GPS.setText("GPS available again\n");
                break;
            case LocationProvider.OUT_OF_SERVICE:
                GPS.setText("GPS out of service\n");
                break;
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                GPS.setText("GPS temporarily unavailable\n");
                break;
            }
        }

        @Override
        public void onProviderEnabled(String provider) {
        	TextView GPS = (TextView) findViewById(R.id.Location_gps);
        	GPS.setText("GPS Provider Enabled\n");
        }

        @Override
        public void onProviderDisabled(String provider) {
        	TextView GPS = (TextView) findViewById(R.id.Location_gps);
        	GPS.setText("GPS Provider Disabled\n");
        }

        @Override
        public void onLocationChanged(Location location) {
            locationManager.removeUpdates(networkLocationListener);
            TextView GPS = (TextView) findViewById(R.id.Location_gps);
            GPS.setText("Location: "
                    + String.format("%9.6f", location.getLatitude()) + ","
                    + String.format("%9.6f", location.getLongitude()) + "\n");

        }
    };
    
    private final LocationListener networkLocationListener = new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        	TextView NetworkText = (TextView) findViewById(R.id.Location_network);
            switch (status) {
            case LocationProvider.AVAILABLE:
            	NetworkText.setText("Network location available again\n");
                break;
            case LocationProvider.OUT_OF_SERVICE:
            	NetworkText.setText("Network location out of service\n");
                break;
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
            	NetworkText.setText("Network location temporarily unavailable\n");
                break;
            }
        }

        @Override
        public void onProviderEnabled(String provider) {
        	TextView NetworkText = (TextView) findViewById(R.id.Location_network);
        	NetworkText.setText("Network Provider Enabled\n");

        }

        @Override
        public void onProviderDisabled(String provider) {
        	TextView NetworkText = (TextView) findViewById(R.id.Location_network);
        	NetworkText.setText("Network Provider Disabled\n");
        }

        @Override
        public void onLocationChanged(Location location) {
        	TextView NetworkText = (TextView) findViewById(R.id.Location_network);
        	NetworkText.setText("Network location: "
                    + String.format("%9.6f", location.getLatitude()) + ","
                    + String.format("%9.6f", location.getLongitude()) + "\n");

        }
    };
	
    @Override
    protected void onResume() {
        super.onResume();

        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, networkLocationListener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, gpsLocationListener);
    }

    @Override
    protected void onPause() {
        super.onPause();

        locationManager.removeUpdates(networkLocationListener);
        locationManager.removeUpdates(gpsLocationListener);
    }
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_result);
		Log.i(ResultActivity.class.toString(), "onCreate");
		Intent intent = getIntent();
		EditText upc = (EditText) findViewById(R.id.upc_code_text);
		upc.setText(intent.getStringExtra(MainActivity.UPC));
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		//Get data from database.
		getProduct(upc.getText().toString());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.result, menu);
		return true;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case IntentIntegrator.REQUEST_CODE: {
			if (resultCode != RESULT_CANCELED) {
				IntentResult scanResult = IntentIntegrator.parseActivityResult(
						requestCode, resultCode, data);
				if (scanResult != null) {
					String upc = scanResult.getContents();

					// put whatever you want to do with the code here
					EditText upcCode = (EditText) findViewById(R.id.upc_code_text);
					upcCode.setText(upc);

				}
			}
			break;
		}
		}
	}

	public void onRegister(View view) {
		registerPrice();
//		if(registerPrice()){
//			Intent intent = this.getIntent();
//			intent.putExtra(MainActivity.REGISTER_RESULT, "Product Registered");
//		}
//    	finish();
    }
	protected boolean getProduct(String barcode)
	{
		queryproductTask oQuery = new queryproductTask();
		try{
			URL ourl = new URL("http://pricewatcher.hlekkur.is/queryproduct.php?barcode="+barcode);
			oQuery.execute(ourl);
			    } catch (Exception e) {
			    	e.printStackTrace();
			    } finally {
			    }
		return true;
	}
	protected boolean registerPrice() {
		DownloadFilesTask oDownload = new DownloadFilesTask();

		//TextView NetworkText = (TextView) findViewById(R.id.Location_network);
		//return true;
		EditText upc = (EditText) findViewById(R.id.upc_code_text);
		EditText product = (EditText) findViewById(R.id.product_text);
		EditText price = (EditText) findViewById(R.id.price_text);

try{
		URL ourl = new URL("http://pricewatcher.hlekkur.is/registerprice.php?barcode="+upc.getText().toString()+"&amount="+price.getText().toString()+"&name="+product.getText().toString());
		oDownload.execute(ourl);
		    } catch (Exception e) {
	e.printStackTrace();
    return false;
} finally {
}
//		StringBuilder builder = new StringBuilder();
//		HttpClient client = new DefaultHttpClient();
//	    HttpGet httpGet = new HttpGet("http://pricewatcher.hlekkur.is/registerprice.php?barcode="+upc.getText().toString()+"&amount="+price.getText().toString()+"&name="+product.getText().toString()); //+"&gps="+NetworkText.getText().toString()
//	    try {
//	      HttpResponse response = client.execute(httpGet);
//	      StatusLine statusLine = response.getStatusLine();
//	      int statusCode = statusLine.getStatusCode();
//	      if (statusCode == 200) {
//	        HttpEntity entity = response.getEntity();
//	        InputStream content = entity.getContent();
//	        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
//	        String line;
//	        while ((line = reader.readLine()) != null) {
//	          builder.append(line);
//	        }
//	      } else {
//	        //Log.e(ScannerActivity.class.toString(), "Failed to download file");
//		    Log.e("Price", "Failed to download file");
//	        return false;
//	      }
//	    } catch (ClientProtocolException e) {
//	      e.printStackTrace();
//	      return false;
//	    } catch (IOException e) {
//	      e.printStackTrace();
//	      return false;
//	    } catch (IllegalStateException e) {
//	    	e.printStackTrace();
//		      return false;
//	    } catch (Exception e) {
//	    	e.printStackTrace();
//		      return false;
//	    } finally {
//	    }	    
//	    
//	    try {
//	        JSONArray jsonArray = new JSONArray(builder.toString());
//	        //Log.i(ScannerActivity.class.getName(),
//	        Log.i("Price",
//	            "Number of entries " + jsonArray.length());
//	        for (int i = 0; i < jsonArray.length(); i++) {
//	          JSONObject jsonObject = jsonArray.getJSONObject(i);
//	          //Log.i(ScannerActivity.class.getName(), jsonObject.getString("text"));
//	          Log.i("Price", jsonObject.getString("text"));
//	        }
//	      } catch (Exception e) {
//	        e.printStackTrace();
//	        return false;
//	      }
		return true;
	}
	 private class DownloadFilesTask extends AsyncTask<URL, Integer, StringBuilder> {
	     protected StringBuilder doInBackground(URL... urls) {
        	 StringBuilder builder = new StringBuilder();
	    	 int count = urls.length;
	         for (int i = 0; i < count; i++) {
	     	    try {

			     		HttpClient client = new DefaultHttpClient();
			     	    HttpGet httpGet = new HttpGet(urls[i].toURI()); //+"&gps="+NetworkText.getText().toString()
	     	    	HttpResponse response = client.execute(httpGet);
	     	      StatusLine statusLine = response.getStatusLine();
	     	      int statusCode = statusLine.getStatusCode();
	     	      if (statusCode == 200) {
	     	        HttpEntity entity = response.getEntity();
	     	        InputStream content = entity.getContent();
	     	        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
	     	        String line;
	     	        while ((line = reader.readLine()) != null) {
	     	          builder.append(line);
	     	        }
	     	      } else {
	     	        //Log.e(ScannerActivity.class.toString(), "Failed to download file");
	     		    Log.e("Price", "Failed to download file");
	     	        //return false;
	     	      }
	     	    } catch (ClientProtocolException e) {
	     	      e.printStackTrace();
	     	      //return false;
	     	    } catch (IOException e) {
	     	      e.printStackTrace();
	     	      //return false;
	     	    } catch (IllegalStateException e) {
	     	    	e.printStackTrace();
	     		      //return false;
	     	    } catch (Exception e) {
	     	    	e.printStackTrace();
	     		      //return false;
	     	    } finally {
	     	    }	    
	     	    
//	             totalSize += Downloader.downloadFile(urls[i]);
//	             publishProgress((int) ((i / (float) count) * 100));
	             // Escape early if cancel() is called
	             if (isCancelled()) break;
	         }
	         return builder;
	         //return totalSize;
	     }

	     protected void onProgressUpdate(Integer... progress) {
	//         setProgressPercent(progress[0]);
	     }

	     protected void onPostExecute(StringBuilder builder) {
//	     	    try {
//	     	    	JSONObject jsonResponse = new JSONObject(builder.toString());
//	     	        JSONArray jsonArray = new JSONArray(jsonResponse.getJSONArray("products").toString());
//	     	        //Log.i(ScannerActivity.class.getName(),
//	     	        Log.i("Price",
//	     	            "Number of entries " + jsonArray.length());
//	     	        for (int i = 0; i < jsonArray.length(); i++) {
//	     	          JSONObject jsonObject = jsonArray.getJSONObject(i);
//	     	          JSONObject jsonProduct = new JSONObject(jsonObject.getJSONObject("product").toString());
//		     	        	//Log.i(ScannerActivity.class.getName(), jsonObject.getString("text"));
//	     	          Log.i("Price", jsonProduct.getString("name"));
//		     			EditText price = (EditText) findViewById(R.id.last_price_text);
//		     			EditText product = (EditText) findViewById(R.id.product_text);
//		     			price.setText(jsonProduct.getString("lastprice"));
//		     			product.setText(jsonProduct.getString("name"));
//	     	        }
//	     	      } catch (Exception e) {
//	     	        e.printStackTrace();
//	     	        //return false;
//	     	      }
	    	 try {
	 	        JSONArray jsonArray = new JSONArray(builder.toString());
	 	        //Log.i(ScannerActivity.class.getName(),
	 	        Log.i("Price",
	 	            "Number of entries " + jsonArray.length());
	 	        for (int i = 0; i < jsonArray.length(); i++) {
	 	          JSONObject jsonObject = jsonArray.getJSONObject(i);
	 	          //Log.i(ScannerActivity.class.getName(), jsonObject.getString("text"));
	 	          Log.i("Price", jsonObject.getString("text"));
	 	        }
	 	      } catch (Exception e) {
	 	        e.printStackTrace();
//	 	        return false;
	 	      }
//	    	 showDialog("Downloaded " + result + " bytes");
	     }
	 }
	 private class queryproductTask extends AsyncTask<URL, Integer, StringBuilder> {
	     protected StringBuilder doInBackground(URL... urls) {
        	 StringBuilder builder = new StringBuilder();
	    	 int count = urls.length;
	         for (int i = 0; i < count; i++) {
	     	    try {

			     		HttpClient client = new DefaultHttpClient();
			     	    HttpGet httpGet = new HttpGet(urls[i].toURI()); //+"&gps="+NetworkText.getText().toString()
	     	    	HttpResponse response = client.execute(httpGet);
	     	      StatusLine statusLine = response.getStatusLine();
	     	      int statusCode = statusLine.getStatusCode();
	     	      if (statusCode == 200) {
	     	        HttpEntity entity = response.getEntity();
	     	        InputStream content = entity.getContent();
	     	        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
	     	        String line;
	     	        while ((line = reader.readLine()) != null) {
	     	          builder.append(line);
	     	        }
	     	      } else {
	     	        //Log.e(ScannerActivity.class.toString(), "Failed to download file");
	     		    Log.e("Price", "Failed to download file");
	     	        //return false;
	     	      }
	     	    } catch (ClientProtocolException e) {
	     	      e.printStackTrace();
	     	      //return false;
	     	    } catch (IOException e) {
	     	      e.printStackTrace();
	     	      //return false;
	     	    } catch (IllegalStateException e) {
	     	    	e.printStackTrace();
	     		      //return false;
	     	    } catch (Exception e) {
	     	    	e.printStackTrace();
	     		      //return false;
	     	    } finally {
	     	    }	    
	     	    
//	             totalSize += Downloader.downloadFile(urls[i]);
//	             publishProgress((int) ((i / (float) count) * 100));
	             // Escape early if cancel() is called
	             if (isCancelled()) break;
	         }
	         return builder;
	         //return totalSize;
	     }

	     protected void onProgressUpdate(Integer... progress) {
	//         setProgressPercent(progress[0]);
	     }

	     protected void onPostExecute(StringBuilder builder) {
	     	    try {
	     	    	JSONObject jsonResponse = new JSONObject(builder.toString());
	     	        JSONArray jsonArray = new JSONArray(jsonResponse.getJSONArray("products").toString());
	     	        //Log.i(ScannerActivity.class.getName(),
	     	        Log.i("Price",
	     	            "Number of entries " + jsonArray.length());
	     	        for (int i = 0; i < jsonArray.length(); i++) {
	     	          JSONObject jsonObject = jsonArray.getJSONObject(i);
	     	          JSONObject jsonProduct = new JSONObject(jsonObject.getJSONObject("product").toString());
		     	        	//Log.i(ScannerActivity.class.getName(), jsonObject.getString("text"));
	     	          Log.i("Price", jsonProduct.getString("name"));
		     			EditText price = (EditText) findViewById(R.id.last_price_text);
		     			EditText product = (EditText) findViewById(R.id.product_text);
		     			price.setText(jsonProduct.getString("lastprice"));
		     			product.setText(jsonProduct.getString("name"));
	     	        }
	     	      } catch (Exception e) {
	     	        e.printStackTrace();
	     	        //return false;
	     	      }

//	    	 showDialog("Downloaded " + result + " bytes");
	     }
	 }
}